var express = require('express');
var resp = require('../config/responseJson');
var Post = require('../model/post');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    let option = {
        isIndexRouter: true,
        user: req.session.user,
        isActivePostLi: 'active'
    };
    Post.find({})
        .sort({ ctime: 'desc' })
        .then(data => {
            option.posts = data;
            if (!option.user) {
                option.resp = ((resp.error.msg = '请先登陆！'), resp.error); //js逗号操作符
                return res.render('layoutPage', option);
            }
            res.render('postPgae', option);
        })
        .catch(err => next(err));
});

router.post('/', function(req, res, next) {
    let post = new Post();
    post.ctime = new Date();
    post.postPersonId = req.session.user._id;
    post.postPersonName = req.session.user.name;
    post.content = req.body.content;
    post.save()
        .then(data => {
            res.json(resp.success);
        })
        .catch(err => {
            next(err);
        });
});

module.exports = router;
